package handlers

import (
	"fmt"
	"jianianhua-server/database"
	"jianianhua-server/models"
	"jianianhua-server/utils"
	"path/filepath"
	"time"

	"github.com/gin-gonic/gin"
)

type ProductHandler struct{}

func NewProductHandler() *ProductHandler {
	return &ProductHandler{}
}


// GetProducts 获取商品列表（返回所有数据，不分页）
func (h *ProductHandler) GetProducts(c *gin.Context) {
	query := database.DB.Model(&models.Product{})

	var total int64
	query.Count(&total)

	var products []models.Product
	err := query.Order("sort ASC, created_at DESC").Find(&products).Error
	if err != nil {
		utils.InternalServerErrorResponse(c, "获取商品列表失败: "+err.Error())
		return
	}

	utils.SuccessResponse(c, gin.H{
		"list":      products,
		"total":     total,
		"page":      1,
		"page_size": len(products),
	})
}

// GetProduct 获取商品详情
func (h *ProductHandler) GetProduct(c *gin.Context) {
	id := c.Param("id")
	
	var product models.Product
	err := database.DB.Where("id = ? AND status = ?", id, 1).First(&product).Error
	if err != nil {
		utils.NotFoundResponse(c, "商品不存在")
		return
	}

	utils.SuccessResponse(c, product)
}

// CreateProduct 创建商品
func (h *ProductHandler) CreateProduct(c *gin.Context) {
	var req struct {
		Name        string  `json:"name" binding:"required"`
		Description string  `json:"description"`
		Price       float64 `json:"price" binding:"required,min=0"`
		Stock       int     `json:"stock" binding:"min=0"`
		Images      string  `json:"images"`
		Sort        int     `json:"sort"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.BadRequestResponse(c, "参数错误: "+err.Error())
		return
	}

	product := models.Product{
		Name:        req.Name,
		Description: req.Description,
		Price:       req.Price,
		Stock:       req.Stock,
		Images:      req.Images,
		Sort:        req.Sort,
		Status:      1,
	}

	err := database.DB.Create(&product).Error
	if err != nil {
		utils.InternalServerErrorResponse(c, "创建商品失败: "+err.Error())
		return
	}

	utils.SuccessResponse(c, product)
}

// UpdateProduct 更新商品
func (h *ProductHandler) UpdateProduct(c *gin.Context) {
	id := c.Param("id")
	
	var req struct {
		Name        string  `json:"name"`
		Description string  `json:"description"`
		Price       float64 `json:"price" binding:"min=0"`
		Stock       int     `json:"stock" binding:"min=0"`
		Images      string  `json:"images"`
		Sort        int     `json:"sort"`
		Status      int     `json:"status"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.BadRequestResponse(c, "参数错误: "+err.Error())
		return
	}

	// 查找商品
	var product models.Product
	err := database.DB.Where("id = ?", id).First(&product).Error
	if err != nil {
		utils.NotFoundResponse(c, "商品不存在")
		return
	}

	// 更新字段
	if req.Name != "" {
		product.Name = req.Name
	}
	if req.Description != "" {
		product.Description = req.Description
	}
	if req.Price > 0 {
		product.Price = req.Price
	}
	if req.Stock >= 0 {
		product.Stock = req.Stock
	}
	if req.Images != "" {
		product.Images = req.Images
	}
	if req.Sort > 0 {
		product.Sort = req.Sort
	}
	// 只有在明确传递status字段且值大于0时才更新状态
	// 这样可以避免前端不传递status时被设置为0
	if req.Status > 0 {
		product.Status = req.Status
	}

	err = database.DB.Save(&product).Error
	if err != nil {
		utils.InternalServerErrorResponse(c, "更新商品失败: "+err.Error())
		return
	}

	utils.SuccessResponse(c, product)
}

// DeleteProduct 删除商品
func (h *ProductHandler) DeleteProduct(c *gin.Context) {
	id := c.Param("id")
	
	var product models.Product
	err := database.DB.Where("id = ?", id).First(&product).Error
	if err != nil {
		utils.NotFoundResponse(c, "商品不存在")
		return
	}

	// 硬删除
	err = database.DB.Unscoped().Delete(&product).Error
	if err != nil {
		utils.InternalServerErrorResponse(c, "删除商品失败: "+err.Error())
		return
	}

	utils.SuccessResponse(c, gin.H{"message": "商品删除成功"})
}

// UploadImage 上传图片
func (h *ProductHandler) UploadImage(c *gin.Context) {
	// 获取上传的文件
	file, err := c.FormFile("image")
	if err != nil {
		utils.BadRequestResponse(c, "获取上传文件失败: "+err.Error())
		return
	}

	// 检查文件类型
	ext := filepath.Ext(file.Filename)
	allowedExts := []string{".jpg", ".jpeg", ".png", ".gif", ".webp"}
	isAllowed := false
	for _, allowedExt := range allowedExts {
		if ext == allowedExt {
			isAllowed = true
			break
		}
	}
	if !isAllowed {
		utils.BadRequestResponse(c, "不支持的文件类型，只支持 jpg, jpeg, png, gif, webp")
		return
	}

	// 检查文件大小 (5MB)
	if file.Size > 5*1024*1024 {
		utils.BadRequestResponse(c, "文件大小不能超过5MB")
		return
	}

	// 生成唯一文件名
	timestamp := time.Now().Unix()
	filename := fmt.Sprintf("product_%d%s", timestamp, ext)
	
	// 保存文件到 uploads 目录
	uploadPath := "uploads/products/"
	
	// 确保目录存在
	if err := utils.EnsureDir(uploadPath); err != nil {
		utils.InternalServerErrorResponse(c, "创建目录失败: "+err.Error())
		return
	}
	
	if err := c.SaveUploadedFile(file, uploadPath+filename); err != nil {
		utils.InternalServerErrorResponse(c, "保存文件失败: "+err.Error())
		return
	}

	// 生成完整的HTTPS URL
	host := c.Request.Host
	if host == "" {
		host = "jianianhua.asia"
	}
	fileURL := fmt.Sprintf("https://%s/uploads/products/%s", host, filename)
	
	utils.SuccessResponse(c, gin.H{
		"url": fileURL,
		"filename": filename,
	})
}
